package com.xiongwei.thread;

import com.xiongwei.pojo.User;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * to do
 *
 * @author XiongWei
 * @date 2021/1/15
 */
public class ThreadLocalTest {

    public static void main(String[] args) throws InterruptedException {
        final ExecutorService executorService = Executors.newFixedThreadPool(3);
        String[] users = {"xw1","xw2","xw3"};
        for (String user : users) {
            executorService.submit(new UserThread(user));
        }
        //主线程会等待其他线程执行完毕后再运行
        executorService.awaitTermination(2, TimeUnit.SECONDS);
        executorService.shutdown();
    }

}

class UserContext implements AutoCloseable{
    final static ThreadLocal<String> userThreadLocal = new ThreadLocal();

    public UserContext(String user){
        userThreadLocal.set(user);
    }

    public static String get(){
        return userThreadLocal.get();
    }

    @Override
    public void close() {
        userThreadLocal.remove();
    }
}

class UserThread extends Thread {

    private String user;

    public UserThread(String user){
        this.user = user;
    }

    @Override
    public void run() {
        try(UserContext userContext = new UserContext(user)){
            new Task1().process();
            new Task2().process();
            new Task3().process();
        };

    }
}

class Task1 {
    public void process() {
        System.out.printf("[%s] check user [%s]...\n", Thread.currentThread().getName(), UserContext.get());
    }
}

class Task2 {
    public void process() {
        System.out.printf("[%s] register user [%s]...\n", Thread.currentThread().getName(), UserContext.get());
    }
}

class Task3 {
    public void process() {
        System.out.printf("[%s] end user [%s]...\n", Thread.currentThread().getName(), UserContext.get());
    }
}